import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000
});

service.interceptors.request.use(
  config => {
    let userStr: string | null = localStorage.getItem('user');
    let user;
    try {
      user = JSON.parse(userStr!);
    } catch (err) {
      user = null;
    }

    if (user && user?.token) {
      config.headers.Authorization = `Bearer ${user?.token}`;
    }

    return config;
  },
  err => Promise.reject(err)
);

/**
 * 响应拦截器
 * 服务端返回数据后, 前端 .then 之前被调用
 */
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { success, data, message } = response.data;
    if (success) {
      return data;
    }

    // TODO 业务请求错误
    return Promise.reject(new Error(message));
  },
  (err: { response: { data: { code: number | string } } }) => {
    if (+err?.response?.data?.code === 401) {
      localStorage.removeItem('user');
      localStorage.removeItem('token');
    }
    return Promise.reject(err);
  }
);

export default <T>(config: AxiosRequestConfig): Promise<T> => service(config);
